<template>
  <div class="baseimg">
    <div class="label">
      请输入BASE64码
    </div>
    <div class="input">
      <el-input type="textarea" v-model="code" :rows="10" disabled></el-input>
    </div>
    <div class="toggle">
      <div><el-button @click="paste">黏贴转化</el-button> </div>
      <div><img :src="src" alt=""></div>
      <div><el-button @click="clear">清空</el-button> </div>
    </div>
    <div class="label">
      信息转二维码
    </div>
    <div class="input">
      <el-input v-model="word" :rows="10"></el-input>
    </div>
    <div class="toggle">
      <el-button @click="getEwm">生成</el-button>
      <el-button @click="download">下载</el-button>
    </div>
    <div v-if="qrCodeUrl != ''">
      <img :src="qrCodeUrl" alt="QR Code" />
    </div>
  </div>
</template>

<script setup>
import QRCode from 'qrcode';
import { ref } from 'vue';
const code = ref('')
const src = ref('')
const word = ref('')
const qrCodeUrl = ref('')
function toggle() {
  src.value = "data:image/png;base64," + code.value
}
function clear() {
  code.value = ""
  src.value = ""
}

function paste() {
  navigator.clipboard // 创建clipboard对象
    .readText() // 调用readText()方法
    .then((clipText) => {
      // 成功回调
      code.value = clipText
      toggle()
      // // console.log(clipText); // clipText是从剪贴板读取到的内容（也就是要粘贴的内容）
    })
    .catch((err) => // console.log("粘贴失败！", err)); // 失败回调
}

async function getEwm() {
  try {
    // 生成二维码并转换为Data URL（Base64编码）
    qrCodeUrl.value = await QRCode.toDataURL(word.value);
  } catch (err) {
    console.error(err);
  }
}

function download() {
  if (qrCodeUrl.value != '') {
    // let blob = new Blob([qrCodeUrl.value]);
    // let downloadElement = document.createElement("a");
    // let href = window.URL.createObjectURL(blob); //创建下载的链接
    // downloadElement.href = href;
    // downloadElement.download = href.original; //下载后文件名
    // document.body.appendChild(downloadElement);
    // downloadElement.click(); //点击下载
    // document.body.removeChild(downloadElement); //下载完成移除元素
    // window.URL.revokeObjectURL(href); //释放掉blob对象
    download2(qrCodeUrl.value, '二维码')
  }
}

function download2 (downloadUrl, name) {
  const aLink = document.createElement('a')
    aLink.style.display = 'none'
    aLink.href = downloadUrl
    aLink.download = name
    // 触发点击-然后移除
    document.body.appendChild(aLink)
    aLink.click()
    document.body.removeChild(aLink)
}
</script>

<style scoped lang="scss">
.baseimg {
  width: 400px;
  height: 400px;
  margin: 10px;

  .input {
    width: 100%;
  }

  .toggle {
    width: 100px;
    margin: 20px 0;
    display: flex;

    >div {
      margin-right: 10px;
    }
  }
}
</style>
